/**
 * 
 */
package edu.tsinghua.mrpvc.device.thermosensor;

import java.util.Calendar;
import java.util.Hashtable;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.osgi.service.event.EventHandler;
import org.osgi.util.tracker.ServiceTracker;

import edu.tsinghua.mrpvc.device.ThermoSensor;
import edu.tsinghua.mrpvc.device.simulate.ThermoSensorSimulateTopic;



/**
 * @author Tangjian Deng & Wei Feng
 *
 */
public class ThermoSensorImpl implements ThermoSensor, EventHandler{
	boolean valid;
	float temperature;
	String ID;
	private ServiceTracker tracker;
	
	public ThermoSensorImpl(BundleContext context, String ID){
		this.ID = ID;
		tracker = new ServiceTracker(context, EventAdmin.class.getName(), null);
		tracker.open();
	}
	@Override
	public String getID() {
		// TODO Auto-generated method stub
		return ID;
	}

	@Override
	public float getTemperature() {
		// TODO Auto-generated method stub
		return temperature;
	}

	@Override
	public boolean isValid() {
		// TODO Auto-generated method stub
		return valid;
	}
	
	public void sense(){
		//System.out.println("ThermoSensor Sensor executed");
		setTemperature((float)20);
	}

	private void generEvent(){
		EventAdmin eventAdmin = (EventAdmin) tracker.getService();
		if(eventAdmin != null){
			Map<String, String> propers = new Hashtable<String, String>();
			propers.put(ThermoSensor.EVENT_PROPER_TMP, (new Float(temperature)).toString());
			propers.put(ThermoSensor.EVENT_PROPER_ID, ID);
			propers.put(ThermoSensor.EVENT_PROPER_ISVALID, ThermoSensor.Constants.ISVALID_TRUE);
			Event event = new Event(ThermoSensor.EVENT_TOPIC_STATE, propers);
			eventAdmin.postEvent(event);
		}
		
	}
	public float setTemperature(float temperature) {
		// TODO Auto-generated method stub
		this.temperature = temperature;
		System.out.println(Calendar.getInstance().getTime().toLocaleString() + 
				" ThermoSensor: sense temperature and posts event");
		generEvent();
		return this.temperature;
	}
	@Override
	public void handleEvent(Event event) {
		// TODO Auto-generated method stub
		if(event.getTopic().equals(ThermoSensor.EVENT_TOPIC_ISVALID)){
			if(event.getProperty(ThermoSensor.EVENT_PROPER_ID) != null && event.getProperty(ThermoSensor.EVENT_PROPER_ID).equals(ID)){
				generEvent();
			}
		}
		else if(event.getTopic().equals(ThermoSensor.EVENT_TOPIC_CURTEMP)){
			if(event.getProperty(ThermoSensor.EVENT_PROPER_ID) != null && event.getProperty(ThermoSensor.EVENT_PROPER_ID).equals(ID)){
				generEvent();
			}
		}		
		else if(event.getTopic().equals(ThermoSensorSimulateTopic.THERMO_SENSE)){
			sense();
		}
	}

}
